/*
 * @(#)QuartzManager.java 2014-10-13 上午11:04:46
 * Copyright 2014 鲍建明, Inc. All rights reserved. 8637.com
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package cn.singno.bob.quartz.dynamic;

import java.util.Date;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;

import cn.singno.bob.quartz.dynamic.entity.DynamicJob;

/**
 * <p>File：QuartzManager.java</p>
 * <p>Title: </p>
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2014 2014-10-13 上午11:04:46</p>
 * <p>Company: 8637.com</p>
 * @author 鲍建明
 * @version 1.0
 */
public class QuartzManager
{
	
	private Scheduler scheduler;
	
	public void setScheduler(Scheduler scheduler)
	{
		this.scheduler = scheduler;
	}

	/**
	 * 开始任务(新增/更新)
	 * @param dynamicJob   自定义的job 
	 * @param paramsMap   传递给job执行的数据 
	 * @param isStateFull   是否是一个同步定时任务，true：同步，false：异步 
	 * @return
	 */
	public  boolean startJob(DynamicJob dynamicJob, JobDataMap paramsMap, boolean isStateFull){
		if(dynamicJob == null){
			return Boolean.FALSE;
		}
		try{
			CronTrigger trigger = getCronTrigger(dynamicJob);
			if(null == trigger){    // 如果不存在该trigger则创建一个  
				JobDetail jobDetail = createJobDetail(dynamicJob, paramsMap, isStateFull);
				trigger = createCronTrigger(dynamicJob); 
				Date date = getScheduler().scheduleJob(jobDetail, trigger);
				System.out.println(date);
			}else {					// Trigger已存在，那么更新相应的定时设置  
				TriggerKey key = trigger.getKey();
				trigger = trigger.getTriggerBuilder().withSchedule(createCronSchedule(dynamicJob.getCronExpression())).build();
				getScheduler().rescheduleJob(key, trigger);
			}
		}
		catch (SchedulerException e){
			e.printStackTrace();			//TODO log
			return Boolean.FALSE;
		}	
		return Boolean.TRUE;
	}
	
	/**
	 * 删除一个任务
	 * @param triggerName
	 * @param jobGroup
	 * @return
	 */
	public boolean deleteJob(String triggerName, String jobGroup){
		try{
			getScheduler().deleteJob(new JobKey(triggerName, jobGroup));
		}
		catch (SchedulerException e){
			e.printStackTrace();
			return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}
	
	/**
	 * 暂停一个任务
	 * @param triggerName
	 * @param jobGroup
	 * @return
	 */
	public boolean stopJob(String triggerName, String jobGroup){
		try{
			getScheduler().pauseJob(new JobKey(triggerName, jobGroup));
		}
		catch (SchedulerException e){
			e.printStackTrace();
			return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}
	
	/**
	 * 暂停所有的任务
	 * @return
	 */
	public boolean stopJobAll(){
		try{
			getScheduler().pauseAll();
		}
		catch (SchedulerException e){
			e.printStackTrace();
			return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}
	
	
	/**
	 * 恢复一个任务
	 * @param triggerName
	 * @param jobGroup
	 * @return
	 */
	public boolean resumeJob(String triggerName, String jobGroup){
		try{
			getScheduler().resumeJob(new JobKey(triggerName, jobGroup));
		}
		catch (SchedulerException e){
			e.printStackTrace();
			return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}
	
	/**
	 * 恢复所有的任务
	 * @return
	 */
	public boolean resumeJobAll(){
		try{
			getScheduler().resumeAll();
		}
		catch (SchedulerException e){
			e.printStackTrace();
			return Boolean.FALSE;
		}
		return Boolean .TRUE;
	}
	
	/**
	 * 得到job的详细信息 
	 * @param jobId
	 * @param jobGroup
	 * @return
	 */
	public JobDetail getJobDetail(String jobId, String jobGroup){
		try{
			return getScheduler().getJobDetail(new JobKey(jobId, jobGroup));
		}
		catch (SchedulerException e){
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 获取指定的触发器
	 * @param triggerName
	 * @param jobGroup
	 * @return
	 */
	public Trigger getTrigger(String triggerName, String jobGroup){
		try{
			return getScheduler().getTrigger(new TriggerKey(triggerName, jobGroup));
		}
		catch (SchedulerException e){
			e.printStackTrace();
			return null;
		}
	}
	
	
	
	/****************************************************** private *****************************************************************/
	
	/**
	 * 创建Job的实例
	 * @param dynamicJob
	 * @param paramsMap
	 * @param isStateFull
	 * @return
	 */
	private JobDetail createJobDetail(DynamicJob dynamicJob, JobDataMap paramsMap, boolean isStateFull){
		 JobBuilder jobBuilder = null;
		 if(isStateFull){
			 jobBuilder = JobBuilder.newJob(dynamicJob.getStateFulljobExecuteClass());
		 }else{
			 jobBuilder = JobBuilder.newJob(dynamicJob.getJobExecuteClass()); 
		 }
		 return jobBuilder.withIdentity(dynamicJob.getJobId(), dynamicJob.getJobGroup()).setJobData(paramsMap).build();
	}
	
	/**
	 *  创建Trigger
	 * @param dynamicJob
	 * @return
	 */
	private CronTrigger createCronTrigger(DynamicJob dynamicJob){
		 CronScheduleBuilder cronScheduleBuilder = createCronSchedule(dynamicJob.getCronExpression());
		 return TriggerBuilder.newTrigger().withIdentity(dynamicJob.getTriggerName(), dynamicJob.getJobGroup()).startNow().withSchedule(cronScheduleBuilder).build();
	}
	
	/**
	 * 创建表达式
	 * @param cronExpression
	 * @return
	 */
	private CronScheduleBuilder createCronSchedule(String cronExpression){
		return CronScheduleBuilder.cronSchedule(cronExpression);
	}
	
	/**
	 * 获取Scheduler
	 * @return
	 */
	public Scheduler getScheduler(){
		return this.scheduler;
	}
	
	/**
	 * 获取CronTrigger
	 * @param dynamicJob
	 * @return
	 * @throws SchedulerException
	 */
	private CronTrigger getCronTrigger(DynamicJob dynamicJob) throws SchedulerException{
		return  (CronTrigger) getScheduler().getTrigger(new TriggerKey(dynamicJob.getTriggerName(), dynamicJob.getJobGroup()));
	}
	
}
